<template>
  <div class="login-container">
    <video
      class="video"
      muted
      src="../../assets/video/lz.mp4"
      loop="loop"
      autoplay="true"
    ></video>
    <div class="bg2"></div>
    <!-- 常规登陆 -->
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title">crm管理系统</h1>
      <i
        @click="isErweiLogin = !isErweiLogin"
        :class="[
          'jiaobiao',
          'iconfont',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <div class="common-login" v-if="!isErweiLogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input
            maxlength="5"
            @keydown.native.13="submitForm('loginForm')"
            v-model="loginForm.captcha"
            class="captcha"
            ref="captcha"
          ></el-input>
          <span
            class="captcha-svg"
            v-html="captchaSvg"
            @click="fetchCaptcha"
          ></span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </div>

      <!-- 二维码切换 -->
      <div class="erwei" v-else>
        <div class="img">
          <img :src="qrDataUrl" width="200px" alt="" />
          <i class="mask" 
          :style="qrStyle" 
          @click="getQrcode"
          v-show="isScanCodeSuccess"></i>
        </div>
        <p>使用手机微信扫码登录</p>
      </div>
    </el-form>
  </div>
</template>
<script>
import * as userApi from "../../api/userss";
import { mapMutations } from "vuex";
// import * as permissionApi from '../../api/permission'
// import allRoutes from '../../router/allRoutes'
// import recursionRoutes from '../../utils/recursionRoutes'

//引入socket.io
//引入生成二维码的插件qrcode

import io from "socket.io-client";
import qrcode from "qrcode";
//引入图片
import codeSuccessImg from "../../assets/img/scancode.png";
import codeInvalidImg from "../../assets/img/invalidQr.png";

//校验函数
var validateCaptcha = (rule, value, callback) => {
  if (!value) {
    callback("验证码不能为空");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  //   console.log(rule);   输入值
  // callback('点尼玛')   传入了参数   说明表单校验不通过    不传参  说明表单校验通过
  //用户名正则，4到16位（字母，数字，下划线，减号）
  var uPattern = /^[a-zA-Z0-9_-]{3,12}$/;
  if (uPattern.test(value)) {
    callback();
  } else {
    callback("用户名:3到16位（字母，数字，下划线，减号");
  }
};
var validatePassword = (rule, value, callback) => {
  if (!value) {
    callback("密码不能为空");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      isErweiLogin: false, // 是否是二维码登录
      qrDataUrl: "", //二维码图片地址
      isScanCodeSuccess: false, //是否扫描二维码成功
      qrStyle: {}, //二维码遮罩样式初始值
      captchaSvg: "",

      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },

  created() {
    //在created这个钩子函数中获取验证码
    this.fetchCaptcha();
  },
  methods: {
    //   aa(){
    // 	  console.log(123);
    //   },

    //映射vuex的方法
    ...mapMutations(["SET_USERINFO"]),

    //封装一个方法，用于获取验证码
    fetchCaptcha() {
      userApi.getCaptchaApi().then((res) => {
        // console.log(res);
        this.captchaSvg = res.data.img;
      });
    },

    submitForm(formName) {
      //验证本地表单是否成功
      this.$refs[formName].validate((valid, unpass) => {
        if (valid) {
          //本地表单校验通过
          //发送登陆请求

          //首先需要发送请求，校验验证码是否正确，
          let { username, password, captcha } = this.loginForm; //将loginForm中的属性解构出来
          //   console.log(captcha.toLowerCase());
          userApi.verifyCaptchApi(captcha.toLowerCase()).then((res) => {
            // console.log('====', res);
            //  新语法    可链入
            //res 是不是undefined  如果不是就继续.data   如果是那就不用往后链入data 了
            if (res?.data?.state) {
              //验证码通过
              //发送登陆请求，进行登陆
              userApi.loginApi({ username, password }).then((res) => {
                // console.log(res);

                if (res.data.state) {
                  //登陆成功后
                  //获取用户菜单（临时写法  为了测试）
                  // this.$store.dispatch('FETCH_MENULIST')
                  // res.data.userInfo包含了当前登录用户信息，这些信息以后会被组建共享

                  //所以可以放到vuex

                  this.SET_USERINFO(res.data.userInfo);

                  //跳转前将用户信息存储到本地

                  // token也要存到本地

                  localStorage.setItem("yf-token", res.data.token);
                  localStorage.setItem(
                    "crm-userInfo",
                    JSON.stringify(res.data.userInfo),
                    //将用户信息添加到vuex
                    this.SET_USERINFO(res.data.userInfo)
                    //跳转到主页
                  );

                  //页面需要进行跳转
                  this.$router.push("./");
                }
              });
            } else {
              // alert('验证码错误')
              //验证码错误 清空验证码 刷新验证码 获得焦点
              this.loginForm.captcha = "";
              this.fetchCaptcha();
              // console.log(this.$refs.captcha);
              this.$refs.captcha.focus();
            }
          });
          //如果正确，那么可以继续发送登陆请求

          //如果不正确，需要有错误提示

          //   console.log(this.loginForm);
          // let {username,password}= this.loginForm;
          // userApi.loginApi({username:this.loginForm.username})
          // userApi.loginApi({username,password})
          // .then(res=>{
          // 	console.log(res);
          // })
        } else {
          //不通过
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //封装一个方法专门用于获取二维码
    async getQrcode(){
      //对遮罩样式初始化
      this.isScanCodeSuccess=false
      //从本地取出sid
      let sid =localStorage.getItem('yf-sid')
      //请求接口 获取二维码url
          let res = await userApi.getQrcodeApi(sid);
          // console.log(res);
          //解构出来二维码URL
          let { scanCodeUrl } = res.data;
          console.log(scanCodeUrl);
          //通过qrcode这个插件  将地址转换为二维码图片
          let erweiImg = await qrcode.toDataURL(scanCodeUrl);
          // console.log(erweiImg);
          this.qrDataUrl = erweiImg;
    }
  },
  watch: {
    //监听切换二维码登录的字段
    isErweiLogin(newVal) {
      //如果newVal是true  表示就是微信扫码登陆
      if (newVal) {
        //建立socket连接
        let socket = io("wss://chst.vip");

        //监听连接成功事件

        socket.on("connectSuccess", async (data) => {
          // console.log(sid);
          let { sid } = data;
          //存到本地
          localStorage.setItem("yf-sid", sid);
          
          this.getQrcode()
        });
        //监听扫码成功事件
        socket.on("scancodeSuccess", async (data) => {
          //显示遮罩
          this.isScanCodeSuccess = true;
          this.qrStyle = {
            backgroundImage: `url(${codeSuccessImg})`,
          };
          // console.log(this.qrStyle);

          // console.log(data);
          let { wechatCode } = data;

          //发起登陆请求

          let res = await userApi.wechatLoginApi(wechatCode);
          console.log(res);

          //解构属性

          let { token, userInfo } = res.data;

          //将token存到本地

          localStorage.setItem("yf-token", token);

          //userInfo存到本地

          localStorage.setItem('userInfo',JSON.stringify(userInfo))

          //将userInfo设置到vuex

          //页面跳转

          this.$router.push('/')

        });

        //监听二维码失效的事件
        
        socket.on('invalidCode',data=>{
          // console.log(data);
          this.isScanCodeSuccess=true;
          this.qrStyle={
            backgroundImage:`url(${codeInvalidImg})`
          }
        })
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login-loginForm {
  width: 400px;
  background-color: rgba(0, 0, 0, 0.5);
  box-sizing: border-box;
  // padding: 20px;
  padding-right: 50px;

  /deep/.el-input__inner {
    width: 250px;
  }
}
.login-container {
  text-align: center;
  color: #fff;
  .common-login {
    padding-right: 50px;
  }
  //二维码样式
  .erwei .img {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
    img {
      position: absolute;
      left: 0;
    }
    .mask {
      width: 100%;
      height: 100%;
      opacity: 0.8;
      background-color: #fff;
      position: absolute;
      left: 0;
      // background-image: url("../../assets/img/scancode.png");
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: center;
      cursor: pointer;
    }
  }
  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: -1px;
    top: -1px;
    cursor: pointer;
    opacity: 0.7;
  }
  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .bg2 {
    // background-image: url("../../assets/img/bg2.png");
    // background-repeat: no-repeat;
    position: fixed;
    width: 20%;
    height: 40%;
    background-size: 100% 100%;
    left: 20%;
    top: 40%;
    opacity: 0.5;
  }
  .el-form {
    position: fixed;
    right: 10%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 100px 0 50px 0;
    /deep/ .el-input__inner {
      width: 250px;
    }
    /deep/ .el-button--primary {
      background: linear-gradient(90deg, #1596fb, #002dff);
      width: 250px;
    }
    /deep/ .el-form-item__label {
      color: #fff;
    }
    .title {
      margin: 0 0 60px 0;
      text-align: center;
      color: #fff;
    }
    /deep/ .captcha {
      width: 100px;
      vertical-align: top;
      .el-input__inner {
        width: 100%;
        height: 45px;
        border-radius: 5px 0 0 5px;
        border: 0;
        font-size: 18px;
      }
    }
    svg path {
      stroke: red;
    }
    .captcha-svg {
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 150px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }
    .el-form-item__content {
      width: 250px !important;
    }
  }
}
</style>


